package procsim;

public class Comparator implements Element{
    private MSignal inSigA, inSigB;
    private Signal gresult, eresult, lresult;

    public Comparator(){
        super();
    }

    public Comparator(MSignal a, MSignal b){
        if(a!=null) a.addElement(this);
        if(b!=null) b.addElement(this);
        inSigA = a;
        inSigB = b;
    }

    public Comparator setA(MSignal sig){
        if(sig!=null) sig.addElement(this);
        inSigA = sig;
        return this;
    }

    public Comparator setB(MSignal sig){
        if(sig!=null) sig.addElement(this);
        inSigB = sig;
        return this;
    }

    public Comparator setGResult(Signal sig){
        gresult=sig;
        return this;
    }

    public Comparator setEResult(Signal sig){
        eresult=sig;
        return this;
    }

    public Comparator setLResult(Signal sig){
        lresult=sig;
        return this;
    }

    @Override
    public Signal result(){
        return eresult;
    }

    @Override
    public Comparator tick(){
        if(inSigA==null || inSigB==null) return this;
        if(inSigA.get()==inSigB.get()){
            if(gresult!=null) gresult.set(0);
            if(eresult!=null) eresult.set(1);
            if(lresult!=null) lresult.set(0);
        } else if(inSigA.get()>inSigB.get()){
            if(gresult!=null) gresult.set(1);
            if(eresult!=null) eresult.set(0);
            if(lresult!=null) lresult.set(0);
        } else {
            if(gresult!=null) gresult.set(0);
            if(eresult!=null) eresult.set(0);
            if(lresult!=null) lresult.set(1);
        }
        return this;
    }

    @Override
    public String toString(){
        return ""+gresult+" "+eresult+" "+lresult;
    }

    @Override public void updateSignal(Sig sig){
        boolean changed = false;
        if(inSigA!=null && inSigA==sig){
            inSigA.set(sig.get(), false);
            changed = true;
        }
        if(inSigB!=null && inSigB==sig){
            inSigB.set(sig.get(), false);
            changed = true;
        }
        if(changed) tick();
    }

}
